import 'package:flutter/material.dart';
import 'package:kxy_flutter_app/auth.dart';
import 'package:kxy_flutter_app/events/events.dart';
import 'package:kxy_flutter_app/model/exam.dart';
import 'package:kxy_flutter_app/model/exam_category.dart';
import 'package:kxy_flutter_app/model/exam_rank.dart';
import 'package:kxy_flutter_app/services/exam_rank_service.dart';

class ExamRankModel with ChangeNotifier {
  Map<int, List<ExamProfile>> _examMap = new Map<int, List<ExamProfile>>();
  Map<int, ExamRank> _rankMap = new Map<int, ExamRank>();

  List<ExamCategory> cateList;
  ExamRankService _rankSrv;

  Future setExamId(int cateIndex, String examId) async {
    _rankMap[cateIndex] = null;
    await getRank(cateIndex, examId: examId);
    notifyListeners();
  }

  Future init() async {
    _rankSrv = new ExamRankService(userId: Auth.instance.userId);
    cateList = await _rankSrv.getExamCateList();

    _rankMap.clear();
    _examMap.clear();
    for (var i = 0; i < cateList.length; i++) {
      _rankMap[i] = null;
      _examMap[i] = null;
    }
  }

  Future<ExamRank> getRank(int cateIndex, {String examId}) async {
    if (_rankMap[cateIndex] == null) {
      _rankMap[cateIndex] = await _rankSrv.getRank(
        cateList[cateIndex].id,
        examId: examId,
      );
    }
    Events.instance.fire(MyExamRankChanged(rank: _rankMap[cateIndex]));
    return _rankMap[cateIndex];
  }

  Future<List<ExamProfile>> getExamList(int cateIndex) async {
    if (_examMap[cateIndex] == null) {
      _examMap[cateIndex] = await _rankSrv.getExamList(cateList[cateIndex].id);
    }
    return _examMap[cateIndex];
  }
}
